import lodash from 'lodash'
import { useMenuStore } from '@/stores/menu'
import router from '@/router/index'
import { findById, findByOfficialName } from '@/apis/auth'
export const findAllMenus = async () => {
  const store = useMenuStore()
  // const store = this
  // const res = await axios({
  //   method: 'get',
  //   url: '/menu/findByOfficialName'
  // })
  // console.log(res.data)
  const res = await findByOfficialName()
  const originMenus = res.data
  store.originMenus = originMenus

  /* loading tree flat */
  const ms: Array<any> = lodash.cloneDeep(originMenus)

  ms.forEach((menu) => {
    menu.children = []
  })

  ms.forEach((menu) => {
    if (menu.pid) {
      const r = ms.find((x) => x.id === menu.pid)
      if (r) {
        r.children.push(menu)
      }
    }
  })
  // console.log(ms)
  const loadedMenus = ms
  store.loadedMenus = loadedMenus
  //      {
  //       path: '/about',
  //       component: () => import('../views/AboutView.vue')
  //     },
  const lm1 = lodash.cloneDeep(loadedMenus)
  const menusForRoute = lm1
    .filter((m) => m.component)
    .map((m) => ({
      path: m.path,
      component: () => import(`../views/${m.component}.vue`)
    }))
  // console.log(menusForRoute)
  store.menusForRoute = menusForRoute
  const appContext = {
    path: '/appContext',
    name: 'appContext',
    component: () => import('../views/AppPage.vue'),
    // redirect: '/home',
    children: menusForRoute
  }
  if (router.hasRoute('appContext')) {
    router.removeRoute('appContext')
  }
  router.addRoute(appContext)
  // for nav
  const lm2 = lodash.cloneDeep(loadedMenus)
  const menusForNav = lm2.filter((x) => x.pid === 0 && x.children.length > 0)
  menusForNav.sort((m1, m2) => m1.priority - m2.priorty)
  // console.log(menusForNav)
  store.menusForNav = menusForNav
}

export const findUltraInfo = async () => {
  const store = useMenuStore()
  // const res = await axios({
  //   url: '/ultraInfo/findById',
  //   method: 'get'
  // })
  const res = await findById()

  store.ultraInfo = res.data
}
